using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class StateMachine {
	
	protected string _nextStateName;
	
	protected States _currentState;
	
	protected Dictionary<string, States> _stateList = new Dictionary<string, States>();
	private bool _changeState = false;
	
	public StateMachine()
	{
		_changeState = false;
		_nextStateName = "none";
	}
	
	public States currentState { get{ return this._currentState; } }
	
	public States GetState( string _name )
	{
		return _stateList[_name];
	}
	
	public States GetState( int _code )
	{
		foreach( KeyValuePair<string, States> st in _stateList )
		{
			if( st.Value.code == _code )
				return st.Value;
		}
		return null;
	}
	
	public int CreateState( string _name, StateMachineDelegate _initFnc, StateMachineDelegate _updateFnc, StateMachineDelegate _finishFnc )
	{
		
		if( _stateList.ContainsKey(_name) )
		{
			Debug.LogError("State \"" + _name + "\" Already exist.");
			return -1;
		}
		
		States _newState = new States( _name, _stateList.Count );
		_newState.init = _initFnc;
		_newState.update = _updateFnc;
		_newState.finish = _finishFnc;
		
		_stateList.Add( _name, _newState );
		
		if( _stateList.Count == 1 )
		{
			_currentState = _newState;
		}
		
		return _newState.code;
	}
	
	public void ChangeState( string _name )
	{
		_nextStateName = _name;
		_changeState = true;
	}
	
	public void SetState( string _name )
	{
		if( _stateList.ContainsKey(_name) )
		{
			if( _currentState != null && _currentState.finish != null )
			{
				_currentState.finish();
			}
			
			States _nextState = _stateList[_name] as States;
			
			if( _nextState.init != null )
			{
				_nextState.init();
			}
			
			_currentState = _nextState;
		}
	}
	
	public void Update()
	{
		_currentState.update();
	}
	
	public void LateUpdate()
	{
		if( _changeState )
		{
			_changeState = false;
			SetState(_nextStateName);
		}
	}
	
}
